<template>
	<el-row>
		<el-col :span="24">
			<el-card>
				<el-row :gutter="20">
					<el-col :span="16">
						<el-button type="success" style="margin-bottom: 10px;" @click="showAddModel">新增</el-button>
					</el-col>
					<el-col :span="8">
						<div class="mt-4">
							<el-input v-model="input" style="max-width: 600px" placeholder="请输入信息"
								class="input-with-select" @input="selectAll(1)">
								<template #prepend>
									<el-select v-model="select" placeholder="选择查询的内容" style="width: 115px">
										<el-option label="手机号" value="mphone" />
										<el-option label="护工名" value="mname" />
										<el-option label="账号" value="musername" />
									</el-select>
								</template>
								<template #append>
									<el-button :icon="Search" />
								</template>
							</el-input>
						</div>
						<!-- <el-input v-model="mname" style="width: 240px; float: right; margin-right: 10px;"
							placeholder="请输入查询的护工" :prefix-icon="Search" clearable @input="selectAll(1)" /> -->
					</el-col>
					<div style="
							height: auto; 
							width: 100%; 
							display: flex; 
							flex-wrap: wrap;
							justify-content: space-around; 
							align-items: center; ">
						<template v-for="medical in medicalAllList" :key="medical.mid">
							<el-card style="
									width:600px; margin-left: 10px; 
									margin-right:5px; margin-bottom: 10px;  
									justify-content: center;
									align-items: center; 
									">
								<template #header>
									<div class="card-header">
										<span>
											{{ medical.mno }}护工详细信息
										</span>
									</div>
								</template>
								<el-descriptions border>
									<el-descriptions-item :rowspan="3" :width="0" label="照片" align="center">
										<el-image style="width: 90px; height: 100px"
											:src="SERVER_ADDR + '/upload/' + medical.picdir" />
									</el-descriptions-item>
									<el-descriptions-item label="姓名">{{ medical.mname }}</el-descriptions-item>
									<el-descriptions-item label="性别">{{ medical.mgender }}</el-descriptions-item>
									<el-descriptions-item label="联系方式" :width="80">{{ medical.mphone
										}}</el-descriptions-item>
									<el-descriptions-item label="状态">
										<span v-if="medical.mstate == 1">
											<el-tag type="success">在职</el-tag>
										</span>
										<span v-else>
											<el-tag type="danger">离职</el-tag>
										</span>
									</el-descriptions-item>
									<el-descriptions-item label="用户名">{{ medical.musername }}</el-descriptions-item>
									<el-descriptions-item label="入职日期">
										{{ medical.entryDate }}
									</el-descriptions-item>
								</el-descriptions>
								<div style="height: 40px; width: 100%;">
									<el-popconfirm title="你确定删除员工吗？" confirm-button-text="确定" cancel-button-text="取消"
										@confirm="delMedical(medical.mid)">
										<template #reference>
											<el-button type="danger"
												style="margin-top: 10px; float: right;">
                        删除
                      </el-button>
										</template>
									</el-popconfirm>
									<el-button type="primary"
										style="margin-top: 10px; margin-right:10px;  float: right;"
										@click="showUpdateMedicalModel(medical.mid)">
                    修改
                  </el-button>
                  <el-button type="warning"
                             style="margin-top: 10px; float: right;"
                             @click="showAddServiceModel(medical.mid)">
                    添加服务
                  </el-button>
								</div>
								<template #footer>
									<el-collapse v-model="activeNames">
										<el-collapse-item title="查看护工的技能" :name="medical.mid">
											<el-table :data="medical.services" border>
												<el-table-column prop="name" label="服务名字" />
												<el-table-column prop="time" label="服务时长">
                          <template #default="scope">
                            {{ scope.row.time }}h
                          </template>
                        </el-table-column>
                        <el-table-column prop="frequency" label="建议频率">
                          <template #default="scope">
                            {{ scope.row.frequency }}
                          </template>
                        </el-table-column>
												<el-table-column label="操作" >
                          <template v-slot="scope">
                            <el-button type="text" @click="showSpec(scope.row.id)">规范书</el-button>
                          </template>
                        </el-table-column>
											</el-table>
										</el-collapse-item>
									</el-collapse>
								</template>
							</el-card>
						</template>
					</div>

					<!-- 分页开始 -->
					<div style="width: 100%; height: auto;">
						<el-row class="row-bg" justify="center">
							<el-col :span="5">
								<div class="grid-content ep-bg-purple" />
							</el-col>
							<el-col :span="8">
								<el-pagination background layout="prev, pager, next" :page-count="medicalAll.pages"
									@change="selectAll" style="margin-top: 10px; margin-left: 30%;"
									v-model:urrent-page="medicalAll.pageNum" />
							</el-col>
							<el-col :span="5">
								<div class="grid-content ep-bg-purple" />
							</el-col>
						</el-row>
					</div>
					<!-- 分页结束 -->
				</el-row>
			</el-card>
		</el-col>
	</el-row>
	<!-- 新增护工对话框开始 -->
	<el-dialog v-model="addDialoadShowMedical" title="新增护工" width="500">
		<el-form :model="addMedical" :rules="rules" ref="addMedicalFrom">
			<el-form-item label="头像" label-width="20%">
				<el-upload class="avatar-uploader" :action="`${SERVER_ADDR}/admin/file/upload`" name="pic"
					:headers="headers" :show-file-list="false" :on-success="handleAvatarSuccessAdd"
					:before-upload="beforeAvatarUpload">
					<img v-if="imageUrlAdd" :src="imageUrlAdd" class="avatar" />
					<el-icon v-else class="avatar-uploader-icon">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="姓名" label-width="20%" prop="mname">
				<el-input v-model="addMedical.mname" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="护工号" label-width="20%" prop="mno">
				<el-input v-model="addMedical.mno" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="用户名" label-width="20%" prop="musername">
				<el-input v-model="addMedical.musername" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="性别" label-width="20%" prop="mgender">
				<el-radio-group v-model="addMedical.mgender">
					<el-radio value="男" border>男</el-radio>
					<el-radio value="女" border>女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="入职日期" label-width="20%">
				<el-date-picker v-model="addMedical.entryDate" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="联系电话" label-width="20%" prop="mphone">
				<el-input v-model="addMedical.mphone" autocomplete="off" style="width: 240px" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="addDialoadShowMedical = false">取消</el-button>
				<el-button type="primary" @click="insertByMedical">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 新增护工对话框结束 -->
	<!-- 修改护工对话框开始 -->
	<el-dialog v-model="updateDialoadShowMedical" title="修改护工" width="500">
		<el-form :model="updateMedical" :rules="rules" ref="updateMedicalFrom">
			<el-form-item label="头像" label-width="20%">
				<el-upload class="avatar-uploader" :action="`${SERVER_ADDR}/admin/file/upload`" name="pic"
					:headers="headers" :show-file-list="false" :on-success="handleAvatarSuccessUpdate"
					:before-upload="beforeAvatarUpload">
					<img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" />
					<el-icon v-else class="avatar-uploader-icon">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="姓名" label-width="20%" prop="mname">
				<el-input v-model="updateMedical.mname" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="护工号" label-width="20%">
				<el-input v-model="updateMedical.mno" autocomplete="off" style="width: 240px" disabled />
			</el-form-item>
			<el-form-item label="用户名" label-width="20%">
				<el-input v-model="updateMedical.musername" autocomplete="off" style="width: 240px" disabled />
			</el-form-item>
			<el-form-item label="性别" label-width="20%" prop="mgender">
				<el-radio-group v-model="updateMedical.mgender">
					<el-radio value="男" border>男</el-radio>
					<el-radio value="女" border>女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="入职日期" label-width="20%">
				<el-date-picker v-model="updateMedical.entryDate" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="联系电话" label-width="20%" prop="mphone">
				<el-input v-model="updateMedical.mphone" autocomplete="off" style="width: 240px" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="updateDialoadShowMedical = false">取消</el-button>
				<el-button type="primary" @click="updateByMedical">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 修改护工对话框结束 -->
  <!-- 规格书的详情开始 -->
  <el-dialog
      v-model="showSpecDialog"
      title="规格书详情"
      width="70%">
    <div v-if="spec">
      <div v-html="spec"></div>
    </div>
    <div v-else>
      <div>规格书不存在</div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showSpecDialog = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 规格书的详情结束 -->
  <!-- 添加服务穿梭框开始 -->
  <el-dialog
      v-model="addServiceModel"
      title="添加服务"
      width="600px">
    <el-transfer
        v-model="updateMedical.serviceIds"
        filterable
        :filter-method="filterService"
        filter-placeholder="服务名字"
        :titles="['可选服务', '已选服务']"
        :props="{
          key: 'id',
          label: 'name'
        }"
        :data="servicesData"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addService">确定</el-button>
        <el-button @click="addServiceModel = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加服务穿梭框结束 -->
</template>
<script setup>
import medicalApi from '@/api/admin/medicalApi.js';
import { ref, computed, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { useTokenStore } from '@/stores/token';
import serviceApi from "@/api/admin/serviceApi.js";
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const addMedicalFrom = ref(null)
const updateMedicalFrom = ref(null)
const tokenStore = useTokenStore();
//上传图片
const headers = computed(() => {
	let token = tokenStore.tokenStr;
	return {
		token
	}
})
const activeNames = ref(['1'])
//定义所有的护工信息
const medicalAll = ref({});
const medicalAllList = ref([]);
//定义查询框
const select = ref('')
const input = ref('')
const showSpecDialog = ref(false);
const spec = ref('');
// 新增服务
const addServiceModel = ref(false)
const servicesData = ref([])
// 查看规格书
const showSpec = (id) => {
  serviceApi.selectById(id)
      .then(
          resp => {
            if (resp.code == 10000) {
              spec.value = resp.data.specification;
              showSpecDialog.value = true;
            }
          }
      )
}
//查询所有的护工信息
const selectAll = (pageNum) => {
	medicalApi.selectAll(pageNum, select.value, input.value)
		.then(resp => {
			medicalAll.value = resp.data
			medicalAllList.value = resp.data.list
		})
}
//显示新增护工对话框
const addDialoadShowMedical = ref(false);
//定于新增护工的绑定数据
const addMedical = ref({
	mno: "",
	mname: "",
	mgender: "",
	mphone: "",
	entryDate: "",
	mstate: 1,
	picdir: "",
	musername: "",
});
//定义显示新增护工对话框的方法
const showAddModel = () => {
	addDialoadShowMedical.value = true
}
//定义新增护工的方法
const insertByMedical = () => {
	if (addMedicalFrom.value) {
		addMedicalFrom.value.validate((valid) => {
			if (valid) {
				medicalApi.insertMedical(addMedical.value)
					.then(resp => {
						if (resp.code == 10000) {
							ElMessage.success(resp.msg)
							addDialoadShowMedical.value = false;
							selectAll(medicalAll.value.pageNum)
						} else {
							ElMessage.error(resp.msg)
						}
					})
			}
		})
	}

}
//定义修改护工的对话框
const updateDialoadShowMedical = ref(false);
//定义修改护工的绑定数据
const updateMedical = ref({});
//定义显示修改护工的对话框
const showUpdateMedicalModel = (mid) => {
	//回显数据
	medicalApi.selebymid(mid)
		.then(resp => {
			updateMedical.value = resp.data
			imageUrlUpdate.value = `${SERVER_ADDR.value}/upload/${resp.data.picdir}`
			//显示对话框
			updateDialoadShowMedical.value = true
		})
}
// 显示新增服务
const showAddServiceModel = (mid) => {
  // 查询已选择的服务
  medicalApi.selebymid(mid)
      .then(resp => {
        if (resp.code == 10000) {
          updateMedical.value = resp.data
          updateMedical.value.serviceIds = resp.data.services.map(service => service.id);
        }
      })
  let service = {};
  // 查询所有的服务
  serviceApi.selectByPage(1,  1000, null, null, service)
      .then(resp => {
        servicesData.value = resp.data.data;
        addServiceModel.value = true
      })

}
const filterService = (query, item) => {
  return item.name.toLowerCase().includes(query.toLowerCase())
}
// 添加护工的服务
const addService = () => {

  medicalApi.updateMedical(updateMedical.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg)
          addServiceModel.value = false
          selectAll(medicalAll.value.pageNum)
        } else{
          ElMessage.error(resp.msg)
        }
      })
}
//定义修改员工的方法
const updateByMedical = () => {
	if (updateMedicalFrom.value) {
		updateMedicalFrom.value.validate((valid) => {
			if (valid) {
				medicalApi.updateMedical(updateMedical.value)
					.then(resp => {
						if (resp.code == 10000) {
							ElMessage.success(resp.msg)
							updateDialoadShowMedical.value = false;
							selectAll(medicalAll.value.pageNum)
						} else {
							ElMessage.error(resp.msg)
						}
					})
			}
		})
	}

}
//定义删除员工的方法
const delMedical = (mid) => {
	// console.log("删除员工")
	medicalApi.delMedical(mid)
		.then(resp => {
			if (resp.code == 10000) {
				ElMessage.success(resp.msg)
				selectAll(medicalAll.value.pageNum)
			} else {
				ElMessage.error(resp.msg)
			}
		})
}
const imageUrlAdd = ref("");
//头像上传的钩子函数
const handleAvatarSuccessAdd = (response, uploadFile) => {
	if (response.code == 10000) {

		ElMessage.success(response.msg);
		imageUrlAdd.value = `${SERVER_ADDR.value}/upload/${response.data}`;
		addMedical.value.picdir = response.data;
	}
}
const imageUrlUpdate = ref("");
const handleAvatarSuccessUpdate = (response, uploadFile) => {
	if (response.code == 10000) {

		ElMessage.success(response.msg);
		imageUrlUpdate.value = `${SERVER_ADDR.value}/upload/${response.data}`;
		updateMedical.value.picdir = response.data;
	}
}

const beforeAvatarUpload = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('只能上传jpg格式的图片')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片大小不能超过2MB')
		return false
	}
	return true
}
//表单验证规则
const rules = reactive({
	mno: [
		{ required: true, message: '请输入员工号', trigger: 'blur' }
	],
	musername: [
		{ required: true, message: '请输入用户名', trigger: 'blur' }
	],
	mname: [
		{ required: true, message: '请输入姓名', trigger: 'blur' }
	],
	mgender: [
		{ required: true, message: '请选择性别', trigger: 'change' }
	],
	mphone: [
		{ required: true, message: '请输入联系方式', trigger: 'blur' },
		{ pattern: /^\d{6,11}$/, message: '联系方式格式不正确', trigger: 'blur' }
	],
});
selectAll(1)
</script>
<style scoped>
.demo-progress .el-progress--line {
	margin-bottom: 10px;
	max-width: 100%;
}

.avatar-uploader,
.avatar {
	width: 178px;
	height: 178px;
	display: block;
	border: 1px dotted #dcdfe6;
	border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
}

.input-with-select .el-input-group__prepend {
	background-color: var(--el-fill-color-blank);
}
</style>